const createError = require('http-errors');
const express = require('express');
const path = require('path');
// 请求体解析
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
// 日志输出
const logger = require('morgan');
// 跨域
const cors = require('cors');
// session
const session = require('express-session');
const indexRouter = require('./routes/index');
// 解析表单
const app = express();

// 跨域
app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 日志输出
app.use(logger('dev'));
// 请求解析
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// session
app.use(
	session({
		secret: 'fafeio',
		resave: true, //访问接口 时间重新计算
		cookie: { secure: false, maxAge: 1000 * 60 * 3, httpOnly: false },
		saveUninitialized: false,
	})
);

// 静态文件
app.use(express.static(path.join(__dirname, 'public')));
// upload 头像img
app.use('/upload', express.static(path.join(__dirname, 'public/upload')));
// 路由
app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
	next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get('env') === 'development' ? err : {};

	// render the error page
	res.status(err.status || 500);
	res.render('error');
});

module.exports = app;
